package org.dbstar.scheduler.identifier;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang.time.DateFormatUtils;
import org.dbstar.scheduler.job.IllegalFactoryException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 标识的工厂类的缺省实现
 * 
 * @author 代波
 * @since 1.0.0
 * @version 1.0.0
 * @date 2012-3-22
 */
public final class DefaultIdentifierFactory implements IdentifierFactory {
	private static final Logger LOGGER = LoggerFactory.getLogger(DefaultIdentifierFactory.class);

	private final String systemIdentifier;
	private final int sequenceLength;
	private final Map<IdentifierType, AtomicInteger> sequenceMap;

	/**
	 * @param dataPattern 系统标识格式化所用的时间模版
	 * @param sequenceLength 序列数值的最小长度
	 */
	public DefaultIdentifierFactory(String dataPattern, int sequenceLength) {
		super();
		this.systemIdentifier = DateFormatUtils.format(System.currentTimeMillis(), dataPattern);
		this.sequenceLength = sequenceLength;
		this.sequenceMap = new HashMap<IdentifierType, AtomicInteger>();
		for (IdentifierType type : IdentifierType.values()) {
			sequenceMap.put(type, new AtomicInteger(0));
		}
		LOGGER.info("DefaultIdentifierFactory inited. SystemIdentifier={}, SequenceLength={}", systemIdentifier,
				sequenceLength);
	}

	@Override
	public Identifier createIdentifier(IdentifierType identifierType) throws IllegalFactoryException {
		try {
			int sequence = sequenceMap.get(identifierType).incrementAndGet();
			return new DefaultIdentifier(identifierType, systemIdentifier, sequence, sequenceLength);
		} catch (Throwable e) {
			throw new IllegalFactoryException(e);
		}
	}

	@Override
	public String getSystemIdentifier() {
		return systemIdentifier;
	}

	public int getSequenceLength() {
		return sequenceLength;
	}
}
